<template>
  <div>
    <FormPanel ref="formPanel" :list="formList" :formType="type" @formChange="formChangeHandle" :isSubmitBtn="false" :collapse="false" labelWidth="110" />
    <BreakSpace label="修改履历" :containerStyle="{ marginBottom: '10px' }" />
    <FilterTable ref="table" :isSelectColumn="false" height="auto" :columns="columns" :dataSource="tableLists" :onColumnsChange="columns => (this.columns = columns)"> </FilterTable>

    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'center'
      }"
    >
      <el-button @click="closeDrawer">关 闭</el-button>
      <multiuse-button type="primary" :click="saveHandler">保 存</multiuse-button>
    </div>
    <BaseDialog :visible.sync="isDealer" title="经销商查询" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <OwnerSearch :type="type" :rowData="formData" @close="emitCloseHandler" />
    </BaseDialog>
  </div>
</template>
<script>
import { dictionary } from '@/utils/dictMixin';
import { selectOne, saveOne, getStockFactor, queryLog } from '@/api/omFinance/FinanceManage/RiskDealerListMaintain';
import { getDealerUser, getRegion } from '@/api/omFinance';
import OwnerSearch from './SearchDealer';
import { numberCheck } from '@/utils/validate';

export default {
  mixins: [dictionary],
  props: ['type', 'rowData'],

  components: {
    OwnerSearch
  },
  data() {
    this.saveData = null;
    return {
      formList: this.createdFrom(),
      columns: this.createdTable(),
      formData: {},
      isDealer: false,
      tableLists: []
    };
  },
  created() {
    this.init();
    this.getDeptData();
    console.log(this.rowData, '---带过来的数据---');
  },
  methods: {
    //加载事业部数据
    async getDeptData() {
      const res = await getRegion();
      if (res.resultCode === 200) {
        let empList = res.data.map(x => ({ text: x.orgName, value: x.id }));
        this.columns.find(item => item.dataIndex === 'deptId').editItems = empList; //操作姓名
        this.columns.find(item => item.dataIndex === 'deptId').filterItems = empList;
        this.formList.find(item => item.fieldName == 'deptId').itemList = empList;
      }
    },
    async getStockFactor(dealerCode) {
      const res = await getStockFactor(dealerCode);
      if (res.resultCode === 200) {
        this.formList.find(item => item.fieldName == 'stockFactor').initialValue = res.data.stockFactor;
      }
    },
    init() {
      if (this.type == 'edit') {
        this.getUser();
        this.getRecordLog();
        this.getDetail(this.rowData.id);
      }
    },
    async getDetail(id) {
      const res = await selectOne(id);
      if (res.resultCode == 200) {
        this.formList.forEach(x => {
          x.initialValue = this.rowData[x.fieldName];
        });
      }
    },
    dealerSearch() {
      this.isDealer = true;
    },
    async getUser() {
      let res = await getDealerUser();
      let empList = res.data.map(x => ({ text: x.employeeName, value: x.userId }));
      this.columns.find(item => item.dataIndex === 'createdBy').editItems = empList; //操作姓名
      this.columns.find(item => item.dataIndex === 'createdBy').filterItems = empList;
    },
    async getRecordLog() {
      const res = await queryLog(this.rowData.id);
      if (res.resultCode == 200) {
        this.tableLists = res.data || [];
      }
    },
    // 保存
    async saveHandler() {
      this.$refs.formPanel.SUBMIT_FORM();
      if (this.saveData !== null) {
        let saveData = Object.assign({}, this.rowData, this.saveData);
        let res = await saveOne(saveData);
        if (res.resultCode === 200) {
          this.closeDrawer('refresh');
        }
      }
    },
    closeDrawer(param) {
      this.$emit('close', false, param);
    },
    emitCloseHandler(val, data) {
      this.isDealer = val;
      if (data) {
        this.getStockFactor(data[0].dealerCode);

        this.formList.find(x => x.fieldName == 'dealerCode').initialValue = data[0].dealerCode;
        this.formList.find(x => x.fieldName == 'dealerName').initialValue = data[0].dealerName;
      }
    },
    formChangeHandle(val) {
      console.log(val, '---表单数据---');
      this.saveData = val;
    },
    selectChangeHandle() {},
    createdFrom() {
      return [
        {
          type: 'SELECT',
          label: '事业部',
          fieldName: 'deptId',
          placeholder: '请输入',
          itemList: []
        },
        {
          type: 'INPUT',
          label: '经销商代码',
          fieldName: 'dealerCode',
          placeholder: '请选择',
          rules: [{ required: true, message: '请选择', trigger: 'change' }],
          readonly: true,
          unitRender: () => {
            return (
              <div>
                <el-button icon="el-icon-search" onClick={() => this.dealerSearch()}></el-button>
              </div>
            );
          }
        },
        {
          type: 'INPUT',
          label: '经销商名称',
          fieldName: 'dealerName',
          placeholder: '',
          readonly: true
        },

        {
          type: 'INPUT_NUMBER',
          label: '移动比例',
          min: 0,
          max: 100,
          fieldName: 'moveRatio',
          placeholder: '请输入',
          rules: [{ trigger: 'blur', validator: numberCheck }]
        },
        {
          type: 'INPUT_NUMBER',
          label: '回款率(%)',
          min: 0,
          max: 100,
          fieldName: 'collectionRate',
          placeholder: '请输入',
          rules: [{ trigger: 'blur', validator: numberCheck }]
        },
        {
          type: 'INPUT',
          label: '库存系数',
          fieldName: 'stockFactor',
          placeholder: '请输入',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '风险理由',
          fieldName: 'riskReason',
          placeholder: '请输入'
        },
        {
          type: 'SELECT',
          label: '启用标记',
          fieldName: 'status',
          placeholder: '请选择',
          itemList: this.createDictList('1003'),
          rules: [{ required: true, message: '请选择', trigger: 'change' }]
        },
        {
          type: 'INPUT',
          label: '管控措施',
          fieldName: 'controlMeasure',
          selfCols: 3,
          placeholder: '请输入'
        },
        {
          type: 'TEXT_AREA',
          label: '备注',
          fieldName: 'remark',
          placeholder: '请输入',
          selfCols: 3,
          maxlength: 200
        }
      ];
    },
    createdTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          fixed: 'left',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '事业部',
          dataIndex: 'deptId',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: [],
          editType: 'select',
          editItems: []
        },
        {
          title: '经销商代码',
          dataIndex: 'dealerCode',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '经销商名称',
          dataIndex: 'dealerName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '移动比例',
          dataIndex: 'moveRatio',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '回款率',
          dataIndex: 'collectionRate',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '风险理由',
          dataIndex: 'riskReason',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '启用标记',
          dataIndex: 'status',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('1003'),
          render: props => {
            return <span>{this.createDictText(props.row.status, '1003')}</span>;
          }
        },
        {
          title: '管控措施',
          dataIndex: 'controlMeasure',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '备注',
          dataIndex: 'riskDealerRemark',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '操作人',
          dataIndex: 'createdBy',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: [],
          editType: 'select',
          editItems: []
        },
        {
          title: '操作时间',
          dataIndex: 'createdAt',
          sorter: true,
          filter: true,
          filterType: 'date-range'
        },
        {
          title: '操作备注',
          dataIndex: 'remark',
          sorter: true,
          filter: true,
          filterType: 'input'
        }
      ];
    }
  }
};
</script>
